<?php
/**
 * 礼券服务类。礼券一般是随订单而撤销的。
 * 
 */ 
class CouponService extends Service {
	public $TAG = 'CouponService.';
	/**
	 * 通过订单id查询所有为撤销的礼券。
	 * @param unknown_type $order_id
	 */
	public function select4UserByOrderId($order_id){
		$map['order_id']=$order_id;
		$map['is_canceled']='N';
		//$map['is_active']='Y';
		$couponlist = model('Coupon')->where($map)->findAll();
		return $couponlist;
	}
	
	
	/**
	 * 通过电话号码查询送礼人。
	 * @param unknown_type $mobile
	 */
	public function select4UserSenderByMobile($mobile,$limit=10){
		if(empty($mobile))return null;
		$where = $this->_sqlWhereByMobile($mobile,'all',true);
		$order_ids = model('Coupon')->where($where)->field('DISTINCT order_id')->findAll();
		foreach($order_ids as $vo){
			$oids[]=$vo['order_id'];
		}
		$uids = service('Order')->select4UserUidsByOids($oids,$limit);
		return $uids;
	}
	
	
	/**
	 * 通过电话号码礼券，查询已发送的礼券
	 * * 参数参见：sqlWhereByMobile()方法说明
	 */
	public function searchByMobile($mobile,$ifused='all',$ifSelectExpired=true,$limit=15){
		$where = $this->_sqlWhereByMobile($mobile,$ifused,$ifSelectExpired);
		$order='start_date desc';
		$pagedata = model('Coupon')->kPageQuery($where,$order,$limit);
		return $pagedata;
	}
	
	/**
	 * 通过mobile查询统一封装查询条件函数
	 * @param String $mobile	电话号码
	 * @param String $ifused	是否使用 空或all=全部 		used=已使用的	unused=未使用的
	 * @param String $ifSelectExpired	查询是否包含过期数据
	 */
	private function _sqlWhereByMobile($mobile,$ifused,$ifSelectExpired){
		$where = " receiver_mobile='".$mobile."'";
		if(empty($ifused)||$ifused=='all'){
			
		}else{
			if($ifused=='unused'){
				$where = $where." and ( checker_id is null or checker_id=0 ) ";
			}else{
				if($ifused=='used') $where = $where." and ( checker_id>0 ) ";
			}
		}
		
		if(!$ifSelectExpired){
			$where = $where." and expired_date > ".time();
		}
		
		$where = $where." and is_send='Y' ";
		$where = $where." and is_canceled='N' ";
		$where = $where." and is_active='Y' ";
		return $where;
	}
	
	/**
	 * 通过电话号码查询礼券总数，查询已发送的礼券
	 * 参数参见：sqlWhereByMobile()方法说明
	 */
	public function countByMobile($mobile,$ifused='all',$ifSelectExpired=false){
		$where = $this->_sqlWhereByMobile($mobile,$ifused,$ifSelectExpired);
		$result = model('Coupon')->where($where)->limit(1)->field('count(1) as count')->find();
		//dump($result);
		$count	=	$result['count'];
		return $count;
	}
	
	/**
	 * 通过礼券号码查询，已经发送并且没有取消的数据。
	 */
	public function getByPasscode($passcode){
		$map['passcode'] = $passcode;
		$map['is_send']='Y';
		//$map['is_canceled']='N';
		$map['is_active']='Y';
		$coupon = model('Coupon')->where($map)->find();
		return $coupon;
	}
	
	
	/**
	 * 商户确认礼券。确认礼卷消费。
	 * @return 成功则返回确认时间，失败返回null。
	 */
	public function checkerConfirm($passcode,$checker_id){
		if(empty($checker_id)||empty($passcode))return null;
		Log::record($TAG.'.checkerConfirm 请求参数$passcode='.$passcode.'  $checker_id='.$checker_id,Log::DEBUG,Log::FILE);
		 
		$coupnodao = model('Coupon');
		$check_time = time();
		$map['checker_id']=$checker_id;
		$map['check_time']=$check_time;
		
		$where['passcode'] = $passcode;
		$where['checker_id'] = array('EXP',' is null or checker_id<1 ');
		$where['is_send']='Y';
		$where['is_canceled']='N';
		$where['is_active']='Y';
		$no = $coupnodao->where($where)->save($map);
		
		Log::record($TAG.'.checkerConfirm sql='.$coupnodao->getLastSql(),Log::DEBUG,Log::FILE);
		Log::save();
		
		if($no){
			//更新相应数据
			$coupon = $this->getByPasscode($passcode);
			D('Partner','Admin')->refreshCheckedNo($checker_id,$coupon['quantity']);
			D('Goods','Admin')->refreshCheckedNo($coupon['goods_id'],$coupon['quantity']);
			return $check_time;
		}
		return null;
	}
	
	/**
	 * 通过ID和手机号码查询。查询条件加入手机号是为了只能接收者查询其所有的礼券。
	 * 取消的状态需要给用户显示。
	 */
	public function getByIdAndMobile($id,$mobile){
		$map['id']=$id;
		$map['receiver_mobile'] = $mobile;
		$map['is_send']='Y';
		$map['is_active']='Y';
		//$map['is_send']='N';
		$coupon = model('Coupon')->where($map)->find();
		return $coupon;
	}
	
	public function search4UserNotUsed($mobile,$limit=15){
		
	}
	
	/**
	 * 系统调用，当商品券已下发成功，修改商品券数据为已发送。
	 * @param unknown_type $ary_couponid
	 */
	public function update4SysHadSended($ary_couponid){
		if(empty($ary_couponid))return;
		$where['id'] = array('in',$ary_couponid);
		$where['is_active']='Y';
		/** 去掉以下两个条件：
		 * 1.记录不管是否取消商品券已发送。可能发送时商品券被取消。
		 * 2.为了支持多次发送去掉$where['is_send']='N';
			$where['is_send']='N';
			$where['is_canceled']='N';
		*/
		$map['is_send']='Y';
		$map['sendtime']=time();
		$coupondao = model('Coupon');
		$no = $coupondao->where($where)->save($map);
		if($no)$coupondao->setInc('send_times',$where);
		return $no;
	}
	
	/**
	 * 通过订单ID查询还未发送的商品券（前提订单已支付）。
	 * 默认条件：当前时间+1小时为时间点，这个时间后未发送的查询出。
	 * @param String $order_id
	 */
	public function select4UserTobeSendByOid($order_id,$limittime=null){
		if( empty($order_id) )return null;
		
		if(!service('Order')->isOrderPaied($order_id))return null;
		
		return $this->selectTobeSend($order_id,$limittime);
		
	}
	
	
	/**
	 * 通过订单ID查询还未发送的商品券（前提订单已支付）。
	 * 默认条件：当前时间为时间点，这个时间后未发送的查询出。
	 * @param String $order_id
	 */
	public function selectTobeSend($order_id=null,$limittime=null,$limit=null){
		Log::record($TAG.'selectTobeSend',Log::DEBUG,Log::FILE);
		Log::record('参数：order_id='.$order_id.'  limittime='.$limittime.'  limit='.$limit,Log::DEBUG,Log::FILE);
		//if(empty($limittime))$limittime=time()+(60*60);
		if(empty($limittime))$limittime=time()+(30*60);
		/**
		$dateAry = paramMillisecond2Ary($limittime);
		if(!empty($order_id)){
			$where = " `order_id`={$order_id} and ";
		}
		$target_date = paramDate( $dateAry['year'].'-'.$dateAry['month'].'-'.$dateAry['day'] );
		$target_hour = intval($dateAry['hour']);

		$where = $where." (`target_date`<{$target_date} or ( `target_date`={$target_date} and `target_hour`<={$target_hour} ) ) and `is_send`='N' and `is_canceled`='N' and `is_active`='Y' ";
		$coupondao = model('Coupon');
		if(!empty($limit))$tobesendList = $coupondao->where($where)->limit($limit)->findAll();
		else $tobesendList = $coupondao->where($where)->findAll();
		Log::record($coupondao->getLastSql(),Log::K_ORDER,Log::FILE);
		**/
		$tobesendList = model('Coupon')->selectCoupon4Send($limittime, $order_id, $limit);
		$tobesendList = $this->_parseCoupon2SendData($tobesendList);
		
		Log::save(); 
		return $tobesendList;
		
	}
	
	/**
	 * 重新发送礼券
	 * 规则：	sender（发送者）：通过订单是否为当前登陆用户来判断是否可以重发。
	 * 			receiver（接收者）：通过当前用户的手机号码于对应订单接收者号码来判断是否可以重发。
	 * 			admin（管理员）：不许作特别判断即可重发。
	 * 除上述规则外，基本规则为：
	 * 			发送次数最多3次。
	 * @param String $id		礼券ID
	 * @param String $oid		订单ID
	 * @param String $mobile	接收者手机号码
	 * @param String $sendRole	重新发送者的角色 (sender,receiver)
	 */
	public function selectCouponReSend4User($id,$oid,$sendRole,$receiver_mobile=null){
		Log::write("CouponService.selectCouponReSend4User(".$id.",".$oid.",".$sendRole.",".$receiver_mobile.")",Log::DEBUG,Log::FILE);
		
		if(!in_array( $sendRole , array('sender','receiver') ))return array('status'=>-1,'msg'=>'请求参数错误！');
		if(empty($id))return array('status'=>-1,'msg'=>'请求参数错误！');
		if(empty($oid))return array('status'=>-1,'msg'=>'请求参数错误！');
		
		//如果为发送者重发
		if($sendRole=='sender'){
			if(!service('Order')->isOrderPaied($oid,$_SESSION['mid']))return array('status'=>-1,'msg'=>'无效订单！');
			//检查订单是否为
			$map['id']=$id;
			$map['order_id']=$oid;
			$tobesendList = model('Coupon')->selectCoupon4ReSend($map);
		}
		//如果为发送者重发
		if($sendRole=='receiver'){
			if(!service('Order')->isOrderPaied($oid))return array('status'=>-1,'msg'=>'无效订单！');
			//检查订单是否为
			$map['id']=$id;
			$map['order_id']=$oid;
			$map['receiver_mobile']=$receiver_mobile;
			$tobesendList = model('Coupon')->selectCoupon4ReSend($map);
		}
		$coupon = $tobesendList[0];
		
		if(empty($coupon))return array('status'=>0,'msg'=>'数据不存在！');
		if($coupon['expired_date']<time())return array('status'=>0,'msg'=>'已过有效期！');
		if($coupon['send_times']>3)return array('status'=>0,'msg'=>'最多能重发三次！');
		if(intval($coupon['checker_id'])>0)return array('status'=>0,'msg'=>'已使用，无须重发！');
		unset($tobesendList);$tobesendList[]=$coupon;
		Log::write("CouponService.selectCouponReSend4User()query data=".parseAry2Str($tobesendList),Log::DEBUG,Log::FILE);
		$tobesendList = $this->_parseCoupon2SendData($tobesendList);

		return array('status'=>1,'msg'=>'','data'=>$tobesendList);
	}
	
	/**
	 * 将要发送的数据，转换为发送中心所需格式
	 */
	private function _parseCoupon2SendData($tobesendList){
		if(!empty($tobesendList)){
			foreach($tobesendList as $vo1){
					$temp_[$vo1['id']] = $vo1 ;
			}
			unset($tobesendList);
				$tobesendList = $temp_;
			//添加发送者、商品、品牌相关信息
			foreach($tobesendList as $vo1){
				if(!in_array($vo1['order_id'],$ary_orderid))$ary_orderid[]=$vo1['order_id'];
			}

			if(!empty($ary_orderid))$ordersInfo = service('Order')->selectORelInfoByIds($ary_orderid);
			Log::record('查询出的数据：',Log::DEBUG,Log::FILE);
			if(!empty($ordersInfo)){
				foreach($tobesendList as $key=>$vo1){
					if($ordersInfo[$vo1['order_id']]['can_send']){
						$result[$key] = $vo1 + $ordersInfo[$vo1['order_id']];
						Log::record(parseAry2Str($result[$key]),Log::DEBUG,Log::FILE);
					}
				}
				unset($ordersInfo);
				unset($tobesendList);
				$tobesendList = $result;
			}
		}
		return $tobesendList;
	}
	
	
	//服务初始化
	public function init($data = '') {
	}
	
	
	//运行服务，系统服务自动运行
	public function run() {
	}
}
?>